<template>
  <div class="address-list">
    <van-address-list v-model="chosenAddressId"
      :list="addressList" 
      default-tag-text="默认" 
     add-button-text="+添加地址"
      @select="onSelect"
      @add="onAdd" 
      @edit="onEdit"  />
  </div>
</template>

<script>
  import {getAddressListAPI} from "@/api/address.js";
  export default {    
    data() {
      return {
        chosenAddressId: "",
        addressList: [],
      };
    },
	
    created() {
      this.chosenAddressId = this.$route.params.addressId || "" ;    
      this.getAddressList();
    },

    methods: {
      //触发增加（此时addressEdit路由功能还没实现）
      onAdd() {
        this.$router.push({
          name: "addressEdit"
        });
      },
      //触发编辑（此时addressEdit路由功能还没实现）
      onEdit(item) {
        this.$router.push({
          name: "addressEdit",
          params: {id: item.id},
        });
      },
      //获取登录用户的收货地址
      getAddressList() {
        getAddressListAPI().then(result => {
          result.data.forEach((item) => {
            let {
              id,
              name,
              tel
            } = item;
            let address =
              item.city + item.county + item.address_detail;
            let isDefault = item.is_default == 1 ? true : false;
            this.addressList.push({
              id,
              name,
              tel,
              address,
              isDefault,
            });
            //默认选择
            if (item.is_default == 1) {
              this.active_id = item.id;
            }
          });
        }).catch(() => {});
      },
      //处理点击列表
      onSelect(item) {
        let addressId = item.id;
        //路由有addressId参数表明是要选择地址id的，把选择结果路由传参返回。
        if (this.$route.params.addressId) {
          this.$router.replace({
            name: "orderCreate",
            params: {
              addressId
            },
          });
        }
      },
    },
  };
</script>

<style scoped lang="less">
  @bgColor: #f8f8f8;
  @mainColor: #ff0000;
  .address-list {
    min-height: 100vh;
    background: @bgColor;
    ::deep .van-address-list {
      margin-top: 5px;
      .van-address-item .van-radio__icon--checked .van-icon {
        background: @mainColor;
        border-color: @mainColor;
      }
      .van-button--danger {
        background: @mainColor;
      }
    }
  }
</style>
